using System;
using System.Text;
using System.Data;
using System.Collections;
using System.Collections.Generic;
using System.Web;
using System.IO;

using Framework;

namespace SchemaDeploy
{
    //Collection Class (Customisable half)
    public partial class CBackupItemList
    {
        #region Filters
        #endregion

        #region Aggregation
        #endregion
        
        #region Searching (Optional)
        //Represents a simple search box to search PK and any string columns (add overloads as required, based on the pattern below)
        //e.g. public CBackupItemList Search(string nameOrId, int backupId, Guid datasetMD5) { ...
        public CBackupItemList Search(string nameOrId)
        {
            //1. Normalisation
            nameOrId = (nameOrId??string.Empty).Trim().ToLower();
            
            //2. Start with a complete list
            CBackupItemList results = this;
            
            //3. Use any available index, such as those generated for fk/bool columns
            //Normal Case - non-unique index (e.g. foreign key)
            //if (int.MinValue != backupId) results = results.GetByBackupId(backupId);
            //if (Guid.Empty != datasetMD5)  results = results.GetByDatasetMD5(datasetMD5);

            //Special case - unique index (e.g. primary key)
            /*
            if (!string.IsNullOrEmpty(nameOrId)) 
            {
                int id;
                if (int.TryParse(nameOrId, out id))
                {
                    CBackupItem obj = this.GetById(id);
                    if (null != obj)
                    {
                        results = new CBackupItemList(1);
                        results.Add(obj);
                        return results;
                    }
                }
            }
            */
            
            //4. Exit early if remaining (non-index) filters are blank
            if (string.IsNullOrEmpty(nameOrId)) return results; 
            
            //5. Manually search each record using custom match logic, building a shortlist
            CBackupItemList shortList = new CBackupItemList();
            foreach (CBackupItem i in results)
                if (Match(nameOrId, i))
                    shortList.Add(i); 
            return shortList;
        }
        //Manual Searching e.g for string-based columns i.e. anything not indexed (add more params if required)
        private bool Match(string name, CBackupItem obj)
        {
            if (!string.IsNullOrEmpty(name)) //Match any string column
            {
                if (null != obj.ItemTableName && obj.ItemTableName.ToLower().Contains(name))   return true;
                return false;   //If filter is active, reject any items that dont match
            }
            return true;    //No active filters (should catch this in step #4)
        }
        #endregion

        #region Cloning
        public CBackupItemList Clone(CDataSrc target) //, int parentId)
        {
            //No Transaction
            if (target is CDataSrcRemote)
                return Clone(target, null); //, parentId);

            //Transaction
            using (IDbConnection cn = target.Local.Connection())
            {
                IDbTransaction tx = cn.BeginTransaction();
                try
                {
                    CBackupItemList clone = Clone(target, tx); //, parentId);
                    tx.Commit();
                    return clone;
                }
                catch
                {
                    tx.Rollback();
                    throw;
                }
            }
        }
        public CBackupItemList Clone(CDataSrc target, IDbTransaction txOrNull) //, int parentId)
        {
            CBackupItemList list = new CBackupItemList(this.Count);
            foreach (CBackupItem i in this)
                list.Add(i.Clone(target, txOrNull)); //, parentId));  *Child entities must reference the new parent
            return list;
        }
        #endregion
        
        #region Export to Csv
        //Note: For non-cached classes like this, should normally use CDataSrc.ExportToCsv(SelectWhere_DataSet)

        //Web 
        //Web - Need to add a project reference to System.Web, or comment out these two methods
        public void ExportToCsv(HttpResponse response) { ExportToCsv(response, "BackupItems.csv"); }
        public void ExportToCsv(HttpResponse response, string fileName)
        {
            CDataSrc.ExportToCsv(response, fileName); //Standard response headers
            StreamWriter sw = new StreamWriter(response.OutputStream);
            ExportToCsv(sw);
            sw.Flush();
            response.End();
        }
        
        //Non-web
        public void ExportToCsv(string filePath)
        {
            StreamWriter sw = new StreamWriter(filePath);
            ExportToCsv(sw);
            sw.Close();
        }

        //Logic
        protected void ExportToCsv(StreamWriter sw)
        {
            string[] headings = new string[] {"ItemId", "ItemBackupId", "ItemTableName", "ItemDatasetXmlGz", "ItemDatasetMD5"};
            CDataSrc.ExportToCsv(headings, sw);
            foreach (CBackupItem i in this)
            {
                object[] data = new object[] {i.ItemId, i.ItemBackupId, i.ItemTableName, i.ItemDatasetXmlGz, i.ItemDatasetMD5};
                CDataSrc.ExportToCsv(data, sw);
            }
        }
        #endregion

        #region Preload Parent Objects
        //Efficiency Adjustment: Preloads the common parent for the whole list, to avoid database chatter 
        public CBackup Backup { set { foreach (CBackupItem i in this) i.Backup = value; } }
        #endregion


        public new void Add(CBackupItem item)
        {
            if (null != _index && !_index.ContainsKey(item.ItemId))
                _index[item.ItemId] = item;

            _indexByTableName = null;
            _indexByBackupId = null;
            _indexByDatasetMD5 = null;
            _indexBySchemaMD5 = null;

            base.Add(item);
        }
        public new void Remove(CBackupItem item)
        {
            if (null != _index && _index.ContainsKey(item.ItemId))
                _index.Remove(item.ItemId);

            _indexByTableName = null;
            _indexByBackupId = null;
            _indexByDatasetMD5 = null;
            _indexBySchemaMD5 = null;

            base.Remove(item);
        }


        //Index by ItemTableName
        public CBackupItem GetByTableName_(string tableName)
        {
            var list = GetByTableName(tableName);
            return list.Count > 0 ? list[0] : null;
        }
        public CBackupItemList GetByTableName(string tableName)
        {
            tableName = Norm(tableName);

            CBackupItemList temp = null;
            if (!IndexByTableName.TryGetValue(tableName, out temp))
            {
                temp = new CBackupItemList();
                IndexByTableName[tableName] = temp;
            }
            return temp;
        }
        private string Norm(string tbl) { return tbl.ToLower().Replace("[", "").Replace("]", ""); }

        [NonSerialized]
        private Dictionary<string, CBackupItemList> _indexByTableName;
        private Dictionary<string, CBackupItemList> IndexByTableName
        {
            get
            {
                if (null == _indexByTableName)
                {
                    Dictionary<string, CBackupItemList> index = new Dictionary<string, CBackupItemList>();
                    CBackupItemList temp = null;
                    foreach (CBackupItem i in this)
                    {
                        var tbl = Norm(i.ItemTableName);
                        if (!index.TryGetValue(tbl, out temp))
                        {
                            temp = new CBackupItemList();
                            index[tbl] = temp;
                        }
                        temp.Add(i);
                    }
                    _indexByTableName = index;
                }
                return _indexByTableName;
            }
        }

    }
}
